﻿#include "jsonviwer.h"
#include "ui_jsonviwer.h"
#include "tabediter.h"
#include "commdefine.h"
#include <QFile>
#include <QFileDialog>
#include <QDir>
#include <QMessageBox>
#include <QDebug>

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif

JsonViwer::JsonViwer(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::JsonViwer),
    m_chooseProj(new SaveProject(this))
{
    ui->setupUi(this);

    ui->centralWidget->setLayout(ui->vlayProject);

    ui->splitter->setStretchFactor(0, 10);
    ui->splitter->setStretchFactor(1, 90);

    connect(m_chooseProj, &SaveProject::newProject, this, &JsonViwer::newProject);
    connect(m_chooseProj, &SaveProject::chooseProject, this, &JsonViwer::chooseProject);

    m_configFileName = QApplication::applicationDirPath() + "/" + g_configName;
    m_config = readConfigFile(m_configFileName);
    loadConfig(m_config);
}

JsonViwer::~JsonViwer()
{
    delete ui;
}


QJsonArray JsonViwer::readConfigFile(const QString &fileName)
{
    QJsonArray obj;
    QFile file(fileName);
    if(file.open(QIODevice::ReadOnly)) {
        obj = QJsonDocument::fromJson(file.readAll()).array();

        file.close();
    }
    else {
        ui->statusBar->showMessage(tr("打开软件配置文件失败"));
        qInfo() << "open config file failed.";
    }
    return obj;
}

void JsonViwer::saveConfigFile(const QString &fileName, const QJsonArray &config)
{
    QFile file(fileName);
    if(file.open(QIODevice::WriteOnly)) {
        QJsonDocument doc(config);
        file.write(doc.toJson());

        file.close();
    }
    else {
        ui->statusBar->showMessage(tr("保存软件配置文件失败"));
        qInfo() << "save config file failed.";
    }
}

void JsonViwer::loadConfig(const QJsonArray &config)
{
    for(auto d : config) {
        QJsonObject obj = d.toObject();
        if("file" == obj["type"].toString()) {
            // file
            QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
            item->setText(0, obj["name"].toString());
        }
        else {
            // project
            QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
            item->setText(0, obj["name"].toString());
            QJsonArray children = obj["file"].toArray();
            for(auto child : children) {
                QJsonObject c = child.toObject();
                if("file" == d["type"].toString()) {
                    // file
                    QTreeWidgetItem *ch = new QTreeWidgetItem(item);
                    ch->setText(0, d["name"].toString());
                }
            }
        }
    }
}

void JsonViwer::switchDocumentPage(const QString filePath)
{
    if(filePath.isEmpty())
        return;
    TabEditer *tab = nullptr;
    bool exist = false;
    for (int i = 0; i < ui->tabWidget->count(); i++) {
        tab = qobject_cast<TabEditer*>(ui->tabWidget->widget(i));
        if(tab->filePath().isEmpty() || tab->filePath() == filePath) {
            tab->setFilePath(filePath);
            ui->tabWidget->setCurrentWidget(tab);

            QString name = getFileNameByPath(filePath);
            name.replace(".json", "");
            ui->tabWidget->tabBar()->setTabText(i, name);
            exist = true;
            break;
        }
    }
    if(!exist) {
        // 不存在，新打开一个页面
        TabEditer *text = new TabEditer(this);
        ui->tabWidget->addTab(text, "new");
        text->setFilePath(filePath);
        ui->tabWidget->setCurrentWidget(text);
    }
}

void JsonViwer::newProject(const QString &filePath)
{
    QString fileName = filePath;
    if(!fileName.contains(".proj"))
        fileName += ".proj";

    // 检查是否重名

    QString name = getFileNameByPath(fileName);
    name.replace(".proj", "");
    QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
    item->setText(0, name);

    // 保存该文件信息
    QJsonObject obj;
    obj["name"] = name;
    obj["path"] = fileName;
    obj["type"] = "project";
    m_config.append(obj);
    saveConfigFile(m_configFileName, m_config);

    // 创建工程文件夹
    QDir dir(fileName);
    if(!dir.exists())
        dir.mkpath(fileName);
}

void chooseProject(const QString &filePath)
{
    qInfo() << filePath;
}

void JsonViwer::on_actionFormat_triggered()
{
    TabEditer *tab = qobject_cast<TabEditer*>(ui->tabWidget->currentWidget());
    QString str = tab->text();
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8());
    QByteArray ba = doc.toJson(QJsonDocument::Indented);
    if(!ba.isEmpty()) {
        tab->setText(doc.toJson(QJsonDocument::Indented));
    }
    else
    {
        QMessageBox::warning(this, tr("警告"), tr("字符串为空或格式错误。"));
    }
}

void JsonViwer::on_actionClearFormat_triggered()
{
    TabEditer *tab = qobject_cast<TabEditer*>(ui->tabWidget->currentWidget());
    QString str = tab->text();
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8());
    QByteArray ba = doc.toJson(QJsonDocument::Compact);
    if(!ba.isEmpty()) {
        tab->setText(doc.toJson(QJsonDocument::Compact));
    }
    else
    {
        QMessageBox::warning(this, tr("警告"), tr("字符串为空或格式错误。"));
    }
}

void JsonViwer::on_tabWidget_tabCloseRequested(int index)
{
    ui->tabWidget->removeTab(index);
}

void JsonViwer::on_actionNewProject_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("新建工程"));

    newProject(fileName);
}

void JsonViwer::on_actionNewDoc_triggered()
{
    TabEditer *text = new TabEditer(this);
    ui->tabWidget->addTab(text, "new");
}

void JsonViwer::on_actionSave_triggered()
{
    // 保存当前文档
    TabEditer *tab = qobject_cast<TabEditer*>(ui->tabWidget->currentWidget());
    if(!tab->text().isEmpty())
    {
        QString fileName;
        if(tab->filePath().isEmpty()) {
            fileName = QFileDialog::getSaveFileName(this, tr("保存"));
            if(!fileName.contains(".json"))
                fileName += ".json";


            // 修改当前标签页名称
            QString name = getFileNameByPath(fileName);
            name.replace(".json", "");
            int index = ui->tabWidget->tabBar()->currentIndex();
            ui->tabWidget->tabBar()->setTabText(index, name);

            // 添加至树结构
            QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
            item->setText(0, name);

            // 保存该文件信息
            QJsonObject obj;
            obj["name"] = name;
            obj["path"] = fileName;
            obj["type"] = "file";
            m_config.append(obj);
            saveConfigFile(m_configFileName, m_config);
        }
        else {
            // 通知保存文件内容
            fileName = tab->filePath();
        }
        tab->saveDocument(fileName);
    }
}

void JsonViwer::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    for(int i = 0; i < m_config.size(); i++) {
        QJsonObject obj = m_config.at(i).toObject();
        if("file" == obj["type"].toString() && item->text(column) == obj["name"].toString()) {
            // 打开文件，已经打开则切换至该页
            switchDocumentPage(obj["path"].toString());
        }
    }
}

void JsonViwer::on_actionOpenDoc_triggered()
{
    m_chooseProj->setConfigInfo(m_config);
}
